package cn.itcast.usermanage.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.abel533.entity.Example;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.itcast.usermanage.mapper.NewUserMapper;
import cn.itcast.usermanage.mapper.UserMapper;
import cn.itcast.usermanage.pojo.EasyUIResult;
import cn.itcast.usermanage.pojo.User;
import cn.itcast.usermanage.service.UserService;
@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private NewUserMapper userMapper;
	@Override
	public EasyUIResult queryEasyUIResult(Integer pageNum, Integer pageSize) {
//		List<User> users = this.userMapper.queryUsersByPage((pageNum-1)*pageSize,pageSize);
		// 在查询方法调用之前，调用分页插件的静态方法，中间最好不要隔任何代码
		PageHelper.startPage(pageNum, pageSize);
		List<User> userList = this.userMapper.select(null);
		// 初始化pageInfo对象，所有的分页参数都可以在该对象中获取
		PageInfo<User> pageInfo = new PageInfo<>(userList);
		EasyUIResult result = new EasyUIResult();
//		result.setRows(users);
		result.setRows(pageInfo.getList());
//		result.setTotal(20l);
		result.setTotal(pageInfo.getTotal());
		return result;
	}
	@Override
	public void addUsers(User user1, User user2) throws Exception {
		this.userMapper.insertSelective(user1);
		// 制造异常
//		int i=1/0;
		this.userMapper.insertSelective(user2);
	}
	@Override
	public boolean addUser(User user) throws Exception {
		int count = this.userMapper.insertSelective(user);
		if(count>0){
			return true;
		}
		return false;
	}
	@Override
	public boolean deleteUser(List<Object> ids) {
		Example example = new Example(User.class);
		example.createCriteria().andIn("id", ids);
		int index = this.userMapper.deleteByExample(example);
		if(index>0){
			return true;
		}
		return false;
	}
	@Override
	public User queryUserById(Long id) {
		return this.userMapper.selectByPrimaryKey(id);
	}
	@Override
	public void saveUser(User user) {
		this.userMapper.insertSelective(user);
	}
	@Override
	public void updateUser(User user) {
		user.setUpdated(new Date());
		this.userMapper.updateByPrimaryKeySelective(user);
	}

}
